package com.tech.koufu.ui.view;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.Request.Method;
import com.android.volley.AuthFailureError; 
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError; 
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.bitmap.PauseOnScrollListener; 
import com.tech.koufu.MyApplication;
import com.tech.koufu.R;
import com.tech.koufu.action.RequestQueueSingleton;
import com.tech.koufu.model.CompetitionGroup;
import com.tech.koufu.tools.CookieStringRequest;
import com.tech.koufu.tools.Statics;
import com.tech.koufu.ui.activity.CompetitionDetailActivity;
import com.tech.koufu.ui.adapter.CompetitionAdapter;

import extras.com.handmark.pulltorefresh.library.PullToRefreshBase;
import extras.com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import extras.com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import extras.com.handmark.pulltorefresh.library.PullToRefreshListView;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils; 
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;

 
/**
 * 比赛列表
 * @author 123
 *
 */
public class CompetitinListView extends Fragment {
	private static final String TAG = CompetitinListView.class.getName();
	private View rootView;

	private PullToRefreshListView mPullToRefreshListView;
	private ListView actualListView;
	private CompetitionAdapter mAdapter;
	private int typeIndex;
	private ArrayList<CompetitionGroup> datas;
//	private RequestQueue mQueue; 
	private MyApplication myApp;
//	CookieStringRequest stringRequest;
	private int page = 1;
	BitmapUtils bitmapUtils;
	public boolean isload = false;
	public boolean isAutoLoad = false;
	public static CompetitinListView newInstance(int index) {
		CompetitinListView hf = new CompetitinListView();
		Bundle bundle = new Bundle();
		bundle.putInt("index", index);
		if(index==3){
			bundle.putBoolean("isAutoLoad", true);
		}
		hf.setArguments(bundle); 
		return hf;
	}
	 
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (rootView == null) {
			Log.v(TAG, "~~~~~~~~~~CompetitinListView~onCreateView~~~~~~");
			rootView = inflater.inflate(R.layout.lv_list_competition, container, false);  
			initView();
			initData(); 
		}
		ViewGroup parent = (ViewGroup) rootView.getParent();
		if (parent != null) {
			parent.removeView(rootView);
		}
	
		return rootView; 
	}
	private void initView() {
		bitmapUtils = new BitmapUtils(getActivity().getApplicationContext());
		myApp = (MyApplication) getActivity().getApplication();
//		mQueue = Volley.newRequestQueue(getActivity().getApplicationContext());  
		typeIndex = getArguments().getInt("index");
		mPullToRefreshListView = (PullToRefreshListView) rootView.findViewById(R.id.lv_stocks);
		actualListView = mPullToRefreshListView.getRefreshableView(); 
        registerForContextMenu(actualListView);
        actualListView.setOnItemClickListener(itemClick);
	}

	private OnItemClickListener itemClick = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			Intent intent = new Intent(getActivity(),CompetitionDetailActivity.class);
			CompetitionGroup cg = datas.get(position-1);
			intent.putExtra("cgBean", cg);
			startActivity(intent);
			
		}
	};
//	private boolean isTopRefresh;
	@Override
	public void onCreate(Bundle savedInstanceState) { 
		super.onCreate(savedInstanceState);
	}
	@Override
	public void onActivityCreated(Bundle savedInstanceState) { 
		super.onActivityCreated(savedInstanceState);
		isAutoLoad = getArguments().getBoolean("isAutoLoad", false);
		if(isAutoLoad){
			manualRefresh(0);
		}
	}
	private void initData() { 
		Log.v(TAG, "~~~~~~~~~~CompetitinListView~initData~~~~~~");
		datas = new ArrayList<CompetitionGroup>();
		mAdapter = new CompetitionAdapter(getActivity().getApplicationContext(),bitmapUtils);
		mAdapter.datas = datas;
		actualListView.setAdapter(mAdapter);  
		mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) { 
				if(mPullToRefreshListView==null)
					return;
				Mode mode = mPullToRefreshListView.getCurrentMode(); 
		        if(mode == Mode.PULL_FROM_START) { 
		        	datas.clear();
		        	page=1; 
		        }else {
		        	page++; 
		        }  
				load(); 
			}
		});  
		mPullToRefreshListView.setOnScrollListener(new PauseOnScrollListener(bitmapUtils, false, true));
		mPullToRefreshListView.setMode(Mode.BOTH); 
		mPullToRefreshListView.setScrollingWhileRefreshingEnabled(true);
	}
	public void manualRefresh(int tag){ 
		if(isload && tag==1 && mPullToRefreshListView!=null){//对应我的大赛，每次进来都重新刷新
			mPullToRefreshListView.setRefreshing(true);
		}
		
		if(!isload && mPullToRefreshListView!=null){ 
			mPullToRefreshListView.setRefreshing(true); 
		} 
	} 
	
	private void load(){
		String url = Statics.URL_PHP;
		if(typeIndex==1){
			url +="group";
		}else{
			url +="myGroup";
		}   
		Log.v(TAG, "~~~~~~~load~~~~~~"+url);
		CookieStringRequest stringRequest = new CookieStringRequest(Method.POST, url, new Listener<String>() {

			@Override
			public void onResponse(String response) {    
				if(!TextUtils.isEmpty(response)){
					try {
//						Log.e("CompetitinList!!!!", response);
						JSONObject obj = new JSONObject(response);
						String status = obj.optString("status");
						if(status.equals("0")){
							JSONArray arry = obj.optJSONArray("data");
							if(arry!=null && arry.length()>0){
								int length = arry.length();
								for(int i=0;i<length;i++){									
									JSONObject o = arry.getJSONObject(i);
//									if(o.optInt("category") != 1){
										CompetitionGroup cg = new CompetitionGroup(o);
										datas.add(cg);
//									}
								}
								mAdapter.datas = datas;
								mAdapter.notifyDataSetChanged();  
							}else{
								page--;
							}
						}else{
							page--; 
						}
					} catch (JSONException e) { 
						e.printStackTrace();
					}
				}
				isload = true;
				mPullToRefreshListView.onRefreshComplete();
				
//				if(isTopRefresh == true){
//					MainActivity mainActivity = (MainActivity) getParentFragment().getActivity();
//					mainActivity.cancleRefreshRotate();
//					isTopRefresh  = false;
//				}
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) { 
				Log.e(TAG, error.getMessage());
				mPullToRefreshListView.onRefreshComplete();
			}
		}){
			@Override
			protected Map<String, String> getParams() throws AuthFailureError { 
				Map<String, String> params = new HashMap<String, String>();
				params.put("page", page+"");    
				if(myApp.isLogin){
					params.put("userID",myApp.getDigitalid());
				}
				Log.v("dasai", myApp.getDigitalid()+"~~~~~~"+page);
				return params;
			}
		};  
		stringRequest.setHeader(myApp.phpsessid);
		RequestQueueSingleton.getInstance(getActivity().getApplicationContext()).addToRequestQueue(stringRequest);
	}

	@Override
	public void onStop() { 
		super.onStop(); 
		Log.v(TAG, "~~~~onStop~~~~~~");
	    RequestQueueSingleton.getInstance(getActivity().getApplicationContext()).cancleAllReq(TAG); 
//		datas.clear();
//		actualListView = null;
//		mPullToRefreshListView = null;
	} 
	
	
}
